﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;

namespace EnumUtilHelpV2
{
    public static class EnumToolV2
    {
        public static string GetDescriptionFromEnumName(this Enum enumName)
        {
            try
            {
                FieldInfo _fieldInfo = enumName.GetType().GetField(enumName.ToString());
                DescriptionAttribute[] _attributes = (DescriptionAttribute[])_fieldInfo.GetCustomAttributes(
                    typeof(DescriptionAttribute), false);
                return (_attributes != null && _attributes.Length > 0) ? _attributes[0].Description : enumName.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("GetDescriptionFromEnumName Exception:{0}", ex.Message.Trim()));
            }
        }
        public static T GetEnumNameFromDescription<T>(string description)
        {
            try
            {
                if (Enum.IsDefined(typeof(T), description))
                {
                    return (T)Enum.Parse(typeof(T), description, true);
                }
                else
                {
                    string[] _enumNames = Enum.GetNames(typeof(T));
                    foreach (string enumName in _enumNames)
                    {
                        object _e = Enum.Parse(typeof(T), enumName);
                        if (description == GetDescriptionFromEnumName((Enum)_e))
                        {
                            return (T)_e;
                        }
                    }
                }
                throw new ArgumentException("description");
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("GetEnumNameFromDescription Exception:{0}", ex.Message.Trim()));
            }
        }
    }
}
